package pdfencrypt;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;

import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.PdfWriter;

public class PdfEncrypt {

	/**
	 * pdf文件加上阅读口令，加上所有者密码
	 * 
	 * @param inputFile
	 * @param userPassWord 用户密码，阅读密码
	 * @param ownerPassWord 所有者密码，安全密码
	 * @return
	 */
	public static OutputStream pdfEncrypt(String inputFile, String userPassWord,
			String ownerPassWord) {
		ByteArrayOutputStream byout = new ByteArrayOutputStream();
		try {
			PdfReader reader = new PdfReader(inputFile);
			PdfStamper stamper = new PdfStamper(reader, byout);
			// 设置密码
			stamper.setEncryption(null,//userPassWord.getBytes()
					/*ownerPassWord.getBytes()*/null, PdfWriter.ALLOW_PRINTING, false);
			stamper.close();
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return byout;
	}

	/**
	 * 输出流转输入流
	 * @param out
	 * @return
	 * @throws Exception
	 */
	public static ByteArrayInputStream outparsein(OutputStream out) throws Exception {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		baos = (ByteArrayOutputStream) out;
		ByteArrayInputStream swapStream = new ByteArrayInputStream(
				baos.toByteArray());
		return swapStream;
	}
	
	public static void main(String[] args) {

		try {

			OutputStream out = pdfEncrypt("F:/Workspace/ItextPDFDemo/pdffolder/个人信用报告.pdf", "xiongfei",
					"randeexiong@");
			InputStream iis = outparsein(out);
			FileOutputStream fos = new FileOutputStream("F:/Workspace/ItextPDFDemo/pdffolder/个人信用报告_encrypt.pdf");
			IOUtils.copy(iis, fos);
			IOUtils.closeQuietly(iis);
			IOUtils.closeQuietly(fos);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}